package com.xique.auth.controller;

import com.xique.api.api.model.LoginApiThirdToken;
import com.xique.auth.bean.request.AccessTokenRequest;
import com.xique.auth.form.LoginBody;
import com.xique.auth.service.SystemLoginService;
import com.xique.common.core.domain.R;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.security.service.ApiTokenService;
import com.xique.system.api.model.LoginSystemUser;
import io.swagger.annotations.ApiModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author shd
 * @create 2021/11/11 11:47
 */
@RestController
@RequestMapping("api")
@ApiModel
@Slf4j
public class ApiTokenController {

    @Autowired
    private ApiTokenService apiTokenService;

    @Autowired
    private SystemLoginService systemLoginService;

    @PostMapping("/login")
    public R<?> login(@RequestBody LoginBody form) {
        // 用户登录
        LoginSystemUser userInfo = systemLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(apiTokenService.createToken(userInfo));
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request) {
        LoginSystemUser loginUser = apiTokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            String username = loginUser.getUserName();
            // 删除用户缓存记录
            apiTokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            systemLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request) {
        // test
        LoginSystemUser loginUser = apiTokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            // 刷新令牌有效期
            apiTokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @PostMapping("/v1/accessToken")
    public R<?> accessToken(@RequestBody AccessTokenRequest request) {
        LoginApiThirdToken loginApiThirdToken = systemLoginService.getAccessToken(request);
        return R.ok(apiTokenService.createAccessToken(loginApiThirdToken));
    }

}
